package finance

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"likeadmin/admin/schemas/req"
	"likeadmin/admin/schemas/resp"
	"likeadmin/constant"
	"likeadmin/core/response"
	"likeadmin/dao"
	"math/rand"
	"strconv"
	"time"
)

type IRefundLogService interface {
	List(c *gin.Context, listReq req.RefundLogListReq) (res []resp.RefundLogResp, e error)
	GenerateSN(prefix string, randSuffixLength int) string
}

// NewRefundLogService 初始化
func NewRefundLogService(db *gorm.DB, dao *dao.Query) IRefundLogService {
	return &refundLogService{db: db, dao: dao}
}

// refundLogService 退款日志服务实现类
type refundLogService struct {
	db  *gorm.DB
	dao *dao.Query
}

// List 退款日志列表
func (srv refundLogService) List(c *gin.Context, listReq req.RefundLogListReq) (res []resp.RefundLogResp, e error) {

	m := srv.dao.RefundLog
	a := srv.dao.SystemAuthAdmin
	q := m.WithContext(c).Where(m.RecordID.Eq(listReq.RecordId))

	// 数据
	objs, err := q.Preload(m.Admin.Select(a.ID, a.Nickname)).Order(m.ID.Desc()).Find()
	if e = response.CheckErr(err, "List Find err"); e != nil {
		return
	}
	var resps []resp.RefundLogResp
	response.Copy(&resps, objs)

	for i, resp := range resps {
		resps[i].RefundStatusText = constant.GetRefundStatusDesc(resp.RefundStatus)
	}

	return resps, nil

}

// GenerateSN 生成随机单号
func (srv refundLogService) GenerateSN(prefix string, randSuffixLength int) string {
	suffix := ""
	for i := 0; i < randSuffixLength; i++ {
		suffix += strconv.Itoa(rand.Intn(10))
	}

	sn := prefix + time.Now().Format("20060102150405") + suffix

	ua := srv.dao.RefundLog
	_, err := ua.Where(ua.Sn.Eq(sn)).Select(ua.Sn).Take()
	if err == gorm.ErrRecordNotFound {
		return sn
	}
	return srv.GenerateSN(prefix, randSuffixLength)

}
